package cosmos.dubbo;

import cosmos.dubbo.domain.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * .
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version 1.0 2017-11-23-0023 13:03
 */
public class DataStore {
    private static final Map<Long, User> USER_STORE = new LinkedHashMap<>(16);

    public static User get(Long id) {
        return USER_STORE.get(id);
    }

    public static Long save(User user) {
        Assert.notNull(user);
        if (null != get(user.getId())) {
            return -1L;
        }

        USER_STORE.put(user.getId(), user);
        return user.getId();
    }

    public static Long delete(Long id) {
        USER_STORE.remove(id);
        return id;
    }

    public static Long update(User user) {
        Assert.notNull(user);
        if (null == get(user.getId())) {
            return -1L;
        }

        USER_STORE.put(user.getId(), user);
        return user.getId();
    }

    public static Page<User> list(Pageable pageable) {
        return new PageImpl<>(new ArrayList<>(USER_STORE.values()), pageable, USER_STORE.size());
    }

    public static Long nextId() {
        Set<Long> keys = USER_STORE.keySet();
        if (keys.size() == 0) {
            return 1L;
        }

        return max(keys.toArray(new Long[keys.size()])) + 1L;
    }

    private static Long max(Long[] array) {
        if (array == null) {
            throw new IllegalArgumentException("The Array must not be null");
        } else if (array.length == 0) {
            throw new IllegalArgumentException("Array cannot be empty.");
        } else {
            Long max = array[0];

            for (int j = 1; j < array.length; ++j) {
                if (array[j] > max) {
                    max = array[j];
                }
            }

            return max;
        }
    }
}
